import type { Recordable, UserInfo } from '@vben/types';

import type { AuthApi } from '#/api';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { LOGIN_PATH } from '@vben/constants';
import { preferences } from '@vben/preferences';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';

import { notification } from 'ant-design-vue';
import { defineStore } from 'pinia';

import { loginApi, logoutApi, phoneLoginApi } from '#/api';
import { $t } from '#/locales';

export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();

  const loginLoading = ref(false);

  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   */
  async function authLogin(
    params: Recordable<any>,
    onSuccess?: () => Promise<void> | void,
  ) {
    // 异步处理用户登录操作并获取 accessToken
    let userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;
      const loginResponse = await loginApi({
        username: params.username,
        password: params.password,
        captcha: params.captcha ?? '',
        checkKey: params.checkKey ?? '',
      });

      debugger;

      const accessToken =
        loginResponse?.token ?? (loginResponse as any)?.data?.token ?? null;

      if (accessToken) {
        accessStore.setAccessToken(accessToken as string);

        const loginUserInfo =
          loginResponse?.userInfo ||
          (loginResponse as any)?.data?.userInfo ||
          {};
        userInfo = transformUserInfo(
          loginUserInfo as AuthApi.LoginResponse['userInfo'],
        );

        userStore.setUserInfo(userInfo);
        accessStore.setAccessCodes([]);

        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        } else {
          onSuccess
            ? await onSuccess?.()
            : await router.push(
                userInfo.homePath || preferences.app.defaultHomePath,
              );
        }

        if (userInfo?.realName) {
          notification.success({
            description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`,
            duration: 3,
            message: $t('authentication.loginSuccess'),
          });
        }
      }
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }

  async function logout(redirect: boolean = true) {
    try {
      await logoutApi();
    } catch {
      // 不做任何处理
    }
    resetAllStores();
    accessStore.setLoginExpired(false);

    // 回登录页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      query: redirect
        ? {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath),
          }
        : {},
    });
  }

  async function authPhoneLogin(
    params: Recordable<any>,
    onSuccess?: () => Promise<void> | void,
  ) {
    let userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;

      const result = await phoneLoginApi({
        mobile: params.mobile,
        smsmode: 2,
        captcha: params.code,
      });

      // debugger;
      const accessToken = result?.token ?? (result as any)?.data?.token ?? null;

      if (accessToken) {
        accessStore.setAccessToken(accessToken as string);

        const loginUserInfo =
          result?.userInfo || (result as any)?.data?.userInfo || {};
        userInfo = transformUserInfo(
          loginUserInfo as AuthApi.LoginResponse['userInfo'],
        );

        debugger;
        userStore.setUserInfo(userInfo);
        accessStore.setAccessCodes([]);

        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        } else {
          onSuccess
            ? await onSuccess?.()
            : await router.push(
                userInfo.homePath || preferences.app.defaultHomePath,
              );
        }

        if (userInfo?.realName) {
          notification.success({
            description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`,
            duration: 3,
            message: $t('authentication.loginSuccess'),
          });
        }
      }
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }

  function $reset() {
    loginLoading.value = false;
  }

  async function fetchUserInfo() {
    return userStore.userInfo;
  }

  function transformUserInfo(raw: AuthApi.LoginResponse['userInfo']): UserInfo {
    return {
      userId: raw.id,
      username: raw.username,
      realName: raw.username,
      avatar: raw.avator ?? '',
      email: raw.email ?? '',
      phone: raw.phone ?? '',
      roles: [],
      companyName: raw.companyName,
      creditCode: raw.creditCode,
      status: raw.status,
      homePath: '/visitor-management',
    } as unknown as UserInfo;
  }

  return {
    $reset,
    authLogin,
    authPhoneLogin,
    fetchUserInfo,
    loginLoading,
    logout,
  };
});
